<template>
  <div class="defense-overlay" :class="{ active: isActive }" @click.self="closePanel">
    <div class="defense-panel">
      <!-- 顶部状态栏 -->
      <div class="top-bar">
        <div class="defense-status-attack">
          <span class="status-indicator"></span>
          <span>连续攻击模拟中</span>
        </div>

        <div class="response-time-attack">
          响应时间: <span class="highlight">{{ responseTime.toFixed(1) }}秒</span>
        </div>
      </div>

      <!-- 面板标题 -->
      <div class="panel-header">
        <h3>AI模拟攻击决策系统</h3>
      </div>

      <!-- 主内容区域 -->
      <div class="defense-flow-container">
        <!-- 时间线区域 -->
        <div class="timeline-container">
          <div class="defense-timeline">
            <transition-group name="fade">
              <div
                  v-for="(step, index) in visibleTimelineSteps"
                  :key="index"
                  class="timeline-item"
              >
                <div class="timeline-icon active">
                  <i :class="step.icon"></i>
                </div>
                <div class="timeline-content">
                  <h4>{{ step.title }}</h4>
                  <p>{{ step.description }}</p>
                  <div v-if="step.details" class="timeline-details">
                    <pre>{{ step.details }}</pre>
                  </div>
                </div>
              </div>
            </transition-group>
          </div>
        </div>

        <!-- 可视化区域 -->
        <div class="visualization-container">
          <!-- 攻击链分析（高度调整） -->
          <div class="attack-chain">
            <h4>攻击链分析 (MITRE ATT&CK)</h4>
            <div class="chain-diagram-container">
              <div class="chain-diagram">
                <transition-group name="fade">
                  <div
                      v-for="(node, i) in visibleAttackChain"
                      :key="i"
                      class="chain-node active"
                      :style="{ left: `${i * 20 + 10}%` }"
                  >
                    <div class="node-index">{{ node.id }}</div>
                    <div class="node-name">{{ node.name }}</div>
                  </div>
                </transition-group>
                <div v-for="(conn, i) in visibleConnectors"
                     :key="'c'+i"
                     class="chain-connector active"
                     :style="{
                       left: `${conn.from * 20 + 20}%`,
                       width: `${20 - 4}%`
                     }">
                  <div class="connector-progress"></div>
                </div>
              </div>
            </div>
          </div>

          <!-- 右下角防御策略区域 -->
          <div class="strategy-container">
            <div class="strategy-visual">
              <div class="strategy-title">防御策略动态优化</div>
              <div class="strategy-content">
                <pre class="strategy-code">{{ currentStrategy }}</pre>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部按钮和状态 -->
      <div class="button-group">
        <div class="buttons-container">
          <button class="download-btn" @click="downloadReport">
            <i class="fas fa-download"></i> 下载完整溯源报告
          </button>
          <button class="regenerate-btn" @click="regenerateStrategy">
            <i class="fas fa-sync-alt"></i> 重新生成防御策略
          </button>
          <button class="report-btn" @click="goToReportPage" style="flex: 2.2; min-width: 200px;">
          <i class="fas fa-file-alt"></i> 生成演练评估报告
          </button>

        </div>

        <div class="strategy-stats-container">
          <div class="stat-item">
            <div class="stat-value">99.8%</div>
            <div class="stat-label">防御成功率</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ responseTime.toFixed(1) }}s</div>
            <div class="stat-label">平均响应</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">0</div>
            <div class="stat-label">误报率</div>
          </div>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: ['isActive'],
  data() {
    return {
      responseTime: 0,
      responseTimer: null,
      timer: null,
      currentStrategy: "// 防御策略初始化中...",
      currentAttackChain: 0,
      currentStep: 0,

      // 第一种攻击链路
      attackChain1: [
        { id: "T1", name: "被动扫描", active: false },
        { id: "T2", name: "主动探测", active: false },
        { id: "T3", name: "SQL注入探测", active: false },
        { id: "T4", name: "XSS探测", active: false },
        { id: "T5", name: "SQL注入利用", active: false },
        { id: "T6", name: "弱密码爆破", active: false },
        { id: "T7", name: "会话劫持", active: false }
      ],

      // 第二种攻击链路
      attackChain2: [
        { id: "T1", name: "被动扫描", active: false },
        { id: "T2", name: "主动探测", active: false },
        { id: "T3", name: "SSH/RDP渗透", active: false },
        { id: "T4", name: "横向移动", active: false },
        { id: "T5", name: "后门植入", active: false },
        { id: "T6", name: "计划任务", active: false },
        { id: "T7", name: "数据窃取", active: false }
      ],

      attackConnectors: [
        { from: 0, to: 1, active: false },
        { from: 1, to: 2, active: false },
        { from: 2, to: 3, active: false },
        { from: 3, to: 4, active: false },
        { from: 4, to: 5, active: false },
        { from: 5, to: 6, active: false }
      ],

      // 第一种攻击链路对应的时间线
      timelineSteps1: [
        {
          title: "被动信息收集",
          description: "检测到攻击者正在收集目标系统信息",
          details: "检测方法: 异常DNS查询模式\n来源IP: 192.168.1.105\n威胁等级: 低",
          active: false,
          icon: "fas fa-search"
        },
        {
          title: "主动探测",
          description: "攻击者正在扫描目标系统开放端口和服务",
          details: "检测方法: 端口扫描特征识别\n扫描频率: 120请求/秒\n防御动作: 限制请求频率",
          active: false,
          icon: "fas fa-bullseye"
        },
        {
          title: "Web漏洞探测",
          description: "检测到SQL注入和XSS探测尝试",
          details: "SQL注入检测点: /login.php\nXSS检测点: /contact.php\n防御动作: WAF规则自动更新",
          active: false,
          icon: "fas fa-shield-alt"
        },
        {
          title: "SQL注入攻击",
          description: "攻击者成功利用SQL注入漏洞",
          details: "漏洞点: /products.php?id=1\n攻击载荷: ' OR 1=1 -- \n防御动作: 数据库防火墙拦截",
          active: false,
          icon: "fas fa-database"
        },
        {
          title: "权限提升尝试",
          description: "检测到弱密码爆破和会话劫持尝试",
          details: "目标账户: admin\n尝试次数: 42次\n防御动作: 账户临时锁定",
          active: false,
          icon: "fas fa-user-lock"
        },
        {
          title: "防御成功",
          description: "攻击链已被成功阻断",
          details: "阻断点: 数据库访问控制\n隔离主机: 3台\n修复动作: 自动打补丁",
          active: false,
          icon: "fas fa-check-circle"
        }
      ],

      // 第二种攻击链路对应的时间线
      timelineSteps2: [
        {
          title: "被动信息收集",
          description: "检测到攻击者正在收集目标系统信息",
          details: "检测方法: 异常DNS查询模式\n来源IP: 192.168.1.105\n威胁等级: 低",
          active: false,
          icon: "fas fa-search"
        },
        {
          title: "主动探测",
          description: "攻击者正在扫描目标系统开放端口和服务",
          details: "检测方法: 端口扫描特征识别\n扫描频率: 150请求/秒\n防御动作: 限制请求频率",
          active: false,
          icon: "fas fa-bullseye"
        },
        {
          title: "横向移动尝试",
          description: "检测到SSH/RDP横向渗透尝试",
          details: "目标服务: SSH (端口22)\n攻击方法: 凭证填充\n防御动作: 多因素认证触发",
          active: false,
          icon: "fas fa-arrows-alt-h"
        },
        {
          title: "持久化尝试",
          description: "检测到后门植入和计划任务创建",
          details: "后门类型: Web Shell\n位置: /var/www/html/.backdoor.php\n防御动作: 文件完整性监控报警",
          active: false,
          icon: "fas fa-history"
        },
        {
          title: "数据窃取尝试",
          description: "检测到异常数据外传行为",
          details: "数据量: 2.4GB\n目标IP: 45.67.89.123\n防御动作: 数据外传阻断",
          active: false,
          icon: "fas fa-file-export"
        },
        {
          title: "防御成功",
          description: "攻击链已被成功阻断",
          details: "阻断点: 网络出口监控\n隔离主机: 5台\n修复动作: 系统镜像恢复",
          active: false,
          icon: "fas fa-check-circle"
        }
      ],

      strategyTemplates: [
        `// 防御策略 - Web攻击防护版
aiDefenseSystem(threat) {
  // 第一阶段: 入侵检测
  if (threat.type === "scanning") {
    activateRateLimiting();
    updateWafRules(threat.signature);
  }

  // 第二阶段: 漏洞利用防护
  if (threat.type === "sql_injection") {
    blockRequest(threat.ip);
    applyVirtualPatch(threat.vulnerability);
    rotateDatabaseCredentials();
  }

  // 第三阶段: 权限防护
  if (threat.type === "privilege_escalation") {
    lockCompromisedAccounts();
    enforceMFA();
    resetSessionTokens();
  }

  // 事后分析
  generateMitreReport(threat);
  updateThreatIntelligence();
}`,
        `// 防御策略 - 横向移动防护版
aiDefenseSystem(threat) {
  // 第一阶段: 入侵检测
  if (threat.type === "scanning") {
    activateNetworkSegmentation();
    deployHoneypots();
  }

  // 第二阶段: 横向移动防护
  if (threat.type === "lateral_movement") {
    isolateCompromisedHosts();
    enforcePrivilegeAccessManagement();
    monitorAnomalousLogins();
  }

  // 第三阶段: 持久化防护
  if (threat.type === "persistence") {
    scanForBackdoors();
    validateCronJobs();
    enforceFileIntegrityMonitoring();
  }

  // 数据保护
  if (threat.type === "data_exfiltration") {
    enableDLP();
    blockSuspiciousConnections();
    encryptSensitiveData();
  }

  // 事后恢复
  initiateIncidentResponse();
  rollbackToKnownGoodState();
}`
      ]
    }
  },
  computed: {
    attackChain() {
      return this.currentAttackChain === 0 ? this.attackChain1 : this.attackChain2;
    },
    timelineSteps() {
      return this.currentAttackChain === 0 ? this.timelineSteps1 : this.timelineSteps2;
    },
    visibleTimelineSteps() {
      return this.timelineSteps.filter(step => step.active);
    },
    visibleAttackChain() {
      return this.attackChain.filter(node => node.active);
    },
    visibleConnectors() {
      return this.attackConnectors.filter(conn => conn.active);
    }
  },
  methods: {
    startDemo() {
      this.resetAll();

      this.responseTime = 0;
      this.currentStep = 0;
      this.responseTimer = setInterval(() => {
        this.responseTime += 0.1;
      }, 100);

      this.timer = setInterval(() => {
        if (this.currentStep < this.timelineSteps.length) {
          // 激活当前步骤
          this.timelineSteps[this.currentStep].active = true;

          // 激活攻击链节点
          if (this.currentStep < this.attackChain.length) {
            this.attackChain[this.currentStep].active = true;
            if (this.currentStep > 0) {
              this.attackConnectors[this.currentStep - 1].active = true;
            }
          }

          // 在聊天界面同步显示防御消息
          const messages = this.currentAttackChain === 0 ? [
            "🚨 检测到信息收集活动! 威胁等级: 低",
            "🛡️ 已激活速率限制对抗主动探测",
            "🔍 检测到SQL注入和XSS探测尝试",
            "⚠️ SQL注入攻击已被阻断 - 数据库防火墙生效",
            "🛑 阻止了权限提升尝试 - 账户已临时锁定",
            "✅ 攻击链已完全阻断 - 系统安全"
          ] : [
            "🚨 检测到信息收集活动! 威胁等级: 低",
            "🛡️ 网络分段已激活对抗扫描",
            "🔍 检测到SSH/RDP横向渗透尝试",
            "⚠️ 后门植入尝试已被阻止 - FIM触发",
            "🛑 数据窃取行为被检测并阻断",
            "✅ 攻击链已完全阻断 - 系统恢复中"
          ];

          if (this.currentStep < messages.length) {
            this.$emit('defense-message', messages[this.currentStep]);
          }

          // 更新防御策略（确保显示）
          if (this.currentStep === this.timelineSteps.length - 1) {
            this.currentStrategy = this.strategyTemplates[this.currentAttackChain];
          }

          this.currentStep++;
        } else {
          clearInterval(this.timer);
          clearInterval(this.responseTimer);
        }
      }, 1000); // 1秒间隔
    },

    resetAll() {
      // 重置所有状态
      this.attackChain1.forEach(item => item.active = false);
      this.attackChain2.forEach(item => item.active = false);
      this.attackConnectors.forEach(conn => conn.active = false);
      this.timelineSteps1.forEach(step => step.active = false);
      this.timelineSteps2.forEach(step => step.active = false);
      this.currentStrategy = "// 防御策略初始化中...";
    },

    goToReportPage() {
      // 关闭当前面板
      this.closePanel();
      // 跳转到/Report页面（需确保路由已配置）
      this.$router.push('/Report');
    },

    regenerateStrategy() {
      this.currentAttackChain = this.currentAttackChain === 0 ? 1 : 0;
      this.startDemo();
    },

    downloadReport() {
      const content = `防御系统报告 - ${new Date().toLocaleString()}\n\n`;
      const chainName = this.currentAttackChain === 0 ?
          "Web攻击链(信息收集→漏洞探测→SQL注入→权限提升)" :
          "横向移动攻击链(信息收集→横向移动→持久化→数据窃取)";

      const fullContent = content +
          `攻击链类型: ${chainName}\n` +
          `检测时间: ${this.responseTime.toFixed(1)}秒\n` +
          `防御策略:\n${this.currentStrategy}`;

      const blob = new Blob([fullContent], { type: 'text/plain' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `防御系统报告_${chainName}.txt`;
      link.click();
    },

    closePanel() {
      this.$emit('close');
      if (this.timer) clearInterval(this.timer);
      if (this.responseTimer) clearInterval(this.responseTimer);
    }
  },
  mounted() {
    if (this.isActive) {
      setTimeout(() => this.startDemo(), 300);
    }
  },
  watch: {
    isActive(newVal) {
      if (newVal) {
        setTimeout(() => this.startDemo(), 300);
      }
    }
  }
}
</script>

<style scoped>
/* 基础样式 */
.defense-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s ease;
}

.report-btn {
  padding: 12px 25px;
  border-radius: 8px;
  border: none;
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 1rem;
}

.defense-overlay.active {
  opacity: 1;
  visibility: visible;
}

.defense-panel {
  width: 90%;
  max-width: 1200px;
  background: linear-gradient(45deg, #ffffff, #7c3aed);
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

/* 顶部状态栏 */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #1e40af;
  color: white;
}

.defense-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-indicator {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #10b981;
  animation: pulse 1.5s infinite;
}

.response-time .highlight {
  font-weight: bold;
  color: #38bdf8;
}

/* 面板标题 */
.panel-header {
  padding: 20px;
  border-bottom: 1px solid #e2e8f0;
}

.panel-header h3 {
  margin: 0;
  color: #1e293b;
  font-size: 1.5rem;
}

/* 主内容区域 */
.defense-flow-container {
  display: flex;
  gap: 20px;
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.timeline-container {
  flex: 1;
  overflow-y: auto;
  padding-right: 10px;
}

.visualization-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
  height: 120%;
}

/* 时间线样式 */
.defense-timeline {
  position: relative;
}

.timeline-item {
  display: flex;
  margin-bottom: 20px;
  padding: 15px;
  border-left: 3px solid #3b82f6;
  background: rgba(59, 130, 246, 0.05);
  border-radius: 0 8px 8px 0;
  transition: all 0.3s ease;
}

.timeline-item:hover {
  background: rgba(59, 130, 246, 0.1);
  transform: translateX(5px);
}

.timeline-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  background: #3b82f6;
  color: white;
  flex-shrink: 0;
}

.timeline-content h4 {
  margin: 0 0 8px 0;
  color: #1e293b;
}

.timeline-content p {
  margin: 0 0 10px 0;
  color: #64748b;
}

.timeline-details {
  background: rgba(255, 255, 255, 0.8);
  padding: 10px;
  border-radius: 6px;
  font-size: 0.85rem;
  border: 1px solid #e2e8f0;
}

.timeline-details pre {
  margin: 0;
  white-space: pre-wrap;
  color: #334155;
}

/* 攻击链样式（高度调整） */
.attack-chain {
  background: #f8fafc;
  padding: 3px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  max-height: 150px;
  display: flex;
  flex-direction: column;
}

.attack-chain h4 {
  margin: 0 0 1px 0;
  color: #1e293b;
  font-size: 1rem;
}

.chain-diagram-container {
  width: 100%;
  overflow-x: auto;
  padding-bottom: 5px;
  flex: 1;
}

.chain-diagram {
  min-width: max-content;
  position: relative;
  padding: 2px 0;
  height: 80px;
}

.chain-node {
  position: absolute;
  top: -25px;
  width: 100px;
  background: white;
  border: 2px solid #3b82f6;
  border-radius: 6px;
  padding: 10px;
  text-align: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  margin: 0 8px 0 8px;
}

.chain-node.active {
  background: #3b82f6;
  color: white;
  top: 15px;
}

.node-index {
  font-weight: bold;
  margin-bottom: 5px;
  font-size: 0.8rem;
}

.node-name {
  font-size: 0.85rem;
}

.chain-connector {
  position: absolute;
  height: 4px;
  background: #cbd5e1;
  top: 28px;
  transform: translateY(-50%);
  transition: all 0.3s ease;
}

.chain-connector.active {
  background: #94a3b8;
}

.connector-progress {
  height: 100%;
  background: #3b82f6;
  width: 0;
  transition: width 1s ease;
}

.chain-connector.active .connector-progress {
  width: 100%;
}

/* 防御策略样式（右下角） */
.strategy-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  top: -45px;
}

.strategy-visual {
  background: #f8fafc;
  padding: 10px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.strategy-title {
  font-weight: bold;
  margin-bottom: 15px;
  color: #1e293b;
  font-size: 1rem;
}

.strategy-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
  flex: 1;
}

.strategy-code {
  background: #1e293b;
  color: #e2e8f0;
  padding: 15px;
  border-radius: 6px;
  font-family: monospace;
  font-size: 0.85rem;
  overflow: auto;
  flex: 1;
  line-height: 1.5;
  white-space: pre-wrap;
}

.strategy-stats-container {
  display: flex;
  gap: 10px;
  align-items: center;
  flex: 1;
  min-width: 300px;
}

.stat-item {
  text-align: center;
  flex: 1;
  padding: 10px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.stat-value {
  font-size: 1.2rem;
  font-weight: bold;
  color: #3b82f6;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.8rem;
  color: #64748b;
}

/* 底部按钮和状态区域 */
.button-group {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 15px;
  padding: 15px 20px;
  border-top: 1px solid #e2e8f0;
  background: #f8fafc;
  flex-wrap: wrap;
}

.buttons-container {
  display: flex;
  gap: 10px;
}

.download-btn, .regenerate-btn {
  padding: 10px 20px;
  border-radius: 6px;
  border: none;
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.download-btn {
  background: #3b82f6;
  color: white;
}

.download-btn:hover {
  background: #2563eb;
}

.regenerate-btn {
  background: #f97316;
  color: white;
}

.regenerate-btn:hover {
  background: #ea580c;
}

/* 动画效果 */
@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

/* 过渡效果 */
.fade-enter-active, .fade-leave-active {
  transition: all 0.5s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .defense-flow-container {
    flex-direction: column;
  }

  .strategy-stats-container {
    flex-direction: column;
    width: 100%;
  }

  .button-group {
    flex-direction: column;
    align-items: stretch;
  }

  .buttons-container {
    width: 100%;
  }

  .download-btn, .regenerate-btn {
    flex: 1;
    justify-content: center;
  }

  .attack-chain {
    max-height: 150px;
  }
}
</style>
